<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
    >
     <el-form-item label="排产状态" prop="planStatus">
        <el-select
          v-model="queryParams.planStatus"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="dict in planStatusList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单合同号" prop="contractCode">
        <el-input
          v-model="queryParams.contractCode"
          placeholder="请输入订单合同号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customName">
        <el-input
          v-model="queryParams.customName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--<el-form-item label="订单日期">
        <el-date-picker
          v-model="daterangeOrderDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>-->

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="handlePlan"
          v-hasPermi="['order:orderinfo:edit']"
          >执行排产</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      border style="width:100%;"
      :data="orderinfoList"
      @selection-change="handleSelectionChange"
    >
    <!--<el-table
        :data="orderinfoList"
        style="width: 100%"
        row-key="id"
        border
        lazy
        :load="load"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">-->
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单合同号" align="center" prop="contractCode" />
      <el-table-column label="客户名称" align="center" prop="customName" />
      <el-table-column label="单据编号" align="center" prop="orderCode" />
      <el-table-column
        label="订单日期"
        align="center"
        prop="orderDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column
        label="创建订单时间"
        align="center"
        prop="orderCreatetime"
      />-->
      <el-table-column label="销售部门" align="center" prop="sailDepart" />
      <el-table-column label="跟单员" align="center" prop="documentaryName" />
      <el-table-column label="业务员" align="center" prop="businessName" />
      <el-table-column label="订单数量" align="center" prop="orderNum" />
      <el-table-column label="已分单数量" align="center" prop="plannedNum" />
      <el-table-column label="排产状态" align="center" prop="planStatus">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.plan_status"
            :value="scope.row.planStatus"
          />
        </template>
      </el-table-column>
      <el-table-column label="预计完成时间" align="center" prop="planFinishdate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planFinishdate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <!-- 0:待创建订单,1:已完成,10:待分单 -->
        <template slot-scope="scope">
         <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.orderStatus == 21 || scope.row.orderStatus == 30"
            @click="handleDetail(scope.row)"
          >排产详情</el-button
          >-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.orderStatus == 21 || scope.row.orderStatus == 30"
            @click="planCancel(scope.row)"
          >取消排产</el-button
          >
          <!--<el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.orderStatus == 20 || scope.row.orderStatus == 21"
            @click="handlePlan(scope.row)"
            v-hasPermi="['order:orderinfo:edit']"
            >执行排产</el-button
          >-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单信息对话框 -->
    <el-dialog
      title="总部排产"
      :visible.sync="open"
      :close-on-click-modal ="false"
      width="1600px"
      append-to-body
    >
      <div style="float: left">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="80px"
          style="margin-bottom: 10px"
        >
         <!-- <el-checkbox v-model="form.chooseSunday">星期天</el-checkbox>-->
          <el-button
            type="primary"
            @click="excutePlan"
            style="margin-left: 20px"
            >排产计算</el-button
          >
        </el-form>
      </div>
      <el-table
        v-loading="loading"
        :data="planOrderinfoList"
        @selection-change="handleSelectionChange"
      >
        <!--<el-table-column type="selection" width="55" align="center" />-->
        <el-table-column label="订单合同号" align="center" prop="contractCode" />
        <el-table-column label="客户名称" align="center" prop="customName" />
        <el-table-column label="单据编号" align="center" prop="orderCode" />
        <el-table-column
          label="订单日期"
          align="center"
          prop="orderDate"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.orderDate, "{y}-{m}-{d}") }}</span>
          </template>
        </el-table-column>
        <!--<el-table-column
          label="创建时间"
          align="center"
          prop="orderCreatetime"
        />-->
        <el-table-column label="销售部门" align="center" prop="sailDepart" />
        <el-table-column label="跟单员" align="center" prop="documentaryName" />
        <el-table-column label="业务员" align="center" prop="businessName" />
        <el-table-column label="订单数量" align="center" prop="orderNum" />
        <!--<el-table-column label="完成时间" align="center" prop="orderNum" />-->
        <el-table-column label="是否满足" align="center" prop="planDesc">
        </el-table-column>
        <el-table-column
          label="预计完成时间"
          align="center"
          prop="planFinishdate"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.planFinishdate, "{y}-{m}-{d}") }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handPlanRemoveOrder(scope.row)"
              v-hasPermi="['order:orderinfo:edit']"
              >移除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!--
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />-->
      <br />
      <br />
      <p style="margin-bottom: 10px">订单排产计算详情</p>
      <template v-for="planItem in planProductVOList">
        <el-tag :type="planItem.typeTag" size="medium"  effect="light">
          产品信息：{{planItem.productCode}} {{planItem.productName}}
        </el-tag>
        <p></p>
        <el-table
          v-loading="loading"
          style="width: 100%"
          row-key="id"
          border
          lazy
          :data="planItem.orderPlanList"
          @selection-change="handleSelectionChange"
          :load="load"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        >
          <el-table-column label="子项物料编码" align="center" prop="bomName" width="220px" />
          <el-table-column label="物料名称" align="center" prop="bomCode" />
          <el-table-column
            label="规格型号"
            align="center"
            prop="productStandard"
          />
          <el-table-column label="单据编号" align="center" prop="orderCode" width="120px"/>
          <el-table-column label="所属分厂" align="center" prop="factoryName" />
          <el-table-column label="班组名称" align="center" prop="teamName" />
          <el-table-column label="订单数量" align="center" prop="productNum" />
          <el-table-column label="分单数量" align="center" prop="workerOrdernum" width="100px">
            <template slot-scope="scope">
              <el-tag type="success">{{scope.row.workerOrdernum}} {{scope.row.bomUnit}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="样品数量" align="center" prop="sampleNum" />
          <!--<el-table-column label="生产用量" align="center" prop="useNum" />-->
          <el-table-column label="库存数量" align="center" prop="storeNum" />
          <el-table-column label="排产数量" align="center" prop="planNum" width="100px">
            <template slot-scope="scope">
              <el-tag type="success">{{scope.row.planNum}} {{scope.row.bomUnit}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="产能情况" align="center" prop="capacityDesc" />
          <el-table-column label="排产开始" align="center" prop="planStartDate" >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.planStartDate, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column label="排产完成" align="center" prop="planEndDate">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.planEndDate, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <!--<el-button 时间
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleDetail(scope.row)"
                v-hasPermi="['order:orderinfo:edit']"
                >排产详情
              </el-button>-->
              <el-button
                v-if="scope.row.levelValue == 1"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleAdjust(scope.row)"
                v-hasPermi="['order:orderinfo:edit']"
              >排产调整
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="submitPlan">提交排产</el-button>
      </div>

      <!-- <pagination
        v-show="plantotal>0"
        :total="plantotal"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      /> -->
    </el-dialog>

    <!-- 排产调整对话框 -->
    <el-dialog
      title="排产调整"
      :visible.sync="adjustopen"
      width="800px"
      append-to-body
    >
      <el-form ref="form2" :model="form2" :rules="rules" label-width="120px">
        <el-row :gutter="5">
          <el-col :span="12">
            <el-form-item label="预计完成时间" prop="planEndDate">
              <el-date-picker
                clearable
                v-model="form2.planEndDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择排产时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 排产详情对话框 -->
    <el-dialog
      title="排产详情"
      :visible.sync="detailopen"
      width="800px"
      append-to-body
    >
    <el-table
        v-loading="loading"
        :data="detailList"
      >
        <el-table-column label="订单编码" align="center" prop="orderCode" />
        <el-table-column label="所属分厂" align="center" prop="factoryName" />
        <el-table-column label="班组名称" align="center" prop="teamName" />
        <el-table-column label="产品名称" align="center" prop="bomName" />
        <el-table-column label="产品编号" align="center" prop="bomCode" />
        <el-table-column label="排产日期" align="center" prop="planDate" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel3">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {
  listPlanOrderinfo,
  getOrderinfo,
  delOrderinfo,
  updateOrderinfo,
  planCancel
} from "@/api/sm/order/orderinfo";
import { excuteOrderPlan, submitPlan ,adjustPlan} from "@/api/sm/order/orderplan";
import { listChildren } from "@/api/sm/basic/bominfo";

export default {
  name: "Orderinfo",
  dicts: ["order_status","plan_status"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      plantotal: 0,
      // 订单信息表格数据
      orderinfoList: [],
      orderinfoResultList: [],
      planOrderinfoList: [],

      // orderplanList: [],

      planProductVOList: [],
      detailList: [],
      planStatusList: [
        { label: "待排产", value: 1 },
        { label: "已排产", value: 2 },
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      adjustopen: false,
      detailopen: false,
      // 同步时间时间范围
      daterangeOrderDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contractCode: null,
        customName: null,
        orderDate: null,
        planStatus: 1,
      },
      // 表单参数
      form: {
        planChooseDate: null,
        orderIds: null,
      },
      // 表单参数
      form1: {
        orderIds: null,
        orderPlanList: null,
      },
      // 表单参数
      form2: {
        mId: null,
        factoryId: null,
        teamId: null,
        planStartDate: null,
        planEndDate: null,
        detailList: []
      },
      // 表单参数
      form3: {
        factoryId: null,
        teamId: null,
        planStartDate: null,
        planEndDate: null,
        adjustStartDate: null,
        adjustEndDate: null,
        detailList: []
      },
      // 表单校验
      rules: {
        planStartDate: [
          { required: true, message: "排产截止时间不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },

  methods: {
    load(tree, treeNode, resolve) {
      console.log(tree);
      let data = {
        "parentBomCode": tree.bomCode,
        "productId": tree.productId,
        "orderCode": tree.orderCode,
        "customName": tree.customName,
        "sampleNum": tree.sampleNum ? tree.sampleNum : 0,
        "workerOrdernum": tree.workerOrdernum ? tree.workerOrdernum : 0,
        // "semiProductPlanNum": tree.semiProductPlanNum ? tree.semiProductPlanNum : tree.planNum
      };
      listChildren(data).then((res) => {   //getChildMenu是我们自己的调用后台的封装
        resolve(                            //resolve是组件的
          res.data  //根据自己的格式,将查到的子菜单数组填充
        )
      })
    },
    handleDetail(row) {
      this.detailopen = true;
      this.detailList=row.detailList;
    },
    handleAdjust(row) {
      this.reset2();
      this.adjustopen = true;
      this.form2.mId = row.index;
      this.form2.planStartDate1 = row.planStartDate;
      this.form2.planEndDate1 = row.planEndDate;
      this.form2.planEndDate = row.planEndDate;
      this.form2.detailList  = row.detailList;
      this.form2.factoryId=row.factoryId;
      this.form2.teamId=row.teamId;
    },
    /** 查询订单信息列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeOrderDate && "" != this.daterangeOrderDate) {
        this.queryParams.params["beginOrderDate"] = this.daterangeOrderDate[0];
        this.queryParams.params["endOrderDate"] = this.daterangeOrderDate[1];
      }
      listPlanOrderinfo(this.queryParams).then((response) => {
        this.orderinfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel2() {
      this.adjustopen = false;
      this.reset2();
    },
    cancel3() {
      this.detailopen = false;
    },

    // 表单重置
    reset2() {
      this.form2 = {
        mId: null,
        factoryId: null,
        teamId: null,
        planStartDate: null,
        planEndDate: null,
        detailList: [],
        planEndDate1: null,
        isDelay: null,
      };
      this.resetForm("form2");
    },
      // 表单重置
    reset3() {
      this.form3 = {
        factoryId: null,
        teamId: null,
        planStartDate: null,
        planEndDate: null,
        adjustStartDate: null,
        adjustEndDate: null,
        detailList: []
      };
      this.resetForm("form3");
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        planChooseDate: null,
        orderIds: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeOrderDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    planCancel(row) {
      this.loading = true;
      const that = this;
      this.$modal.confirm(`确认要取消 \n [ ${row.orderDate} - ${row.orderCode} ] \n 总部排产吗？`).then(function() {
        planCancel({
          "orderCode": row.orderCode,
          "productId": row.id,
          "productCode": row.productCode
        }).then(response => {
          that.loading = false;
          that.$modal.msgSuccess("取消成功");
          that.getList();
        }).catch(() => {
          that.loading = false;
        });
      }).then(() => {
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 执行排产操作 */
    handlePlan(row) {
      this.loading = true;
      const ids = row.id || this.ids;
      // this.orderplanList = [];
      this.planProductVOList = [];
      listPlanOrderinfo({ ids: ids + "" }).then((response) => {
        this.planOrderinfoList = response.rows;
        this.open = true;
        this.title = "待排产订单";
        this.loading = false;
      });
    },
    handPlanRemoveOrder(row) {
      const id = row.id;
      this.planOrderinfoList.map((item, index) => {
        if (item.id == id) this.planOrderinfoList.splice(index, 1); //index 当前元素索引；1：需要删除的元素个数
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getOrderinfo(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单信息";
      });
    },
    excutePlan() {
      if (this.planOrderinfoList.length == 0) {
        alert("无排产订单");
        return;
      }
      this.loading = true;
      this.form.orderIds = this.planOrderinfoList
        .map((item) => item.id)
        .join(",");
      excuteOrderPlan(this.form).then((response) => {
        // this.orderplanList = response.data.orderPlanList;
        this.planProductVOList = response.data.planProductVOList || [];

        // 初始化id
        // this.orderplanList.forEach((item, ix) => {
        //   this.$set(this.orderplanList[ix], "mId", ix);
        // });

        this.orderinfoResultList = response.data.orderInfoList;
        this.setOrderPlanResult();
        this.loading = false;
        this.$modal.msgSuccess("排产成功");
        //this.open = false;
        //this.getList();
      }) .catch(() => {
        this.loading = false;
      });;
    },

    setOrderPlanResult() {
      this.planOrderinfoList.forEach((obj) => {
        this.orderinfoResultList.map((item, index) => {
          if (item.orderCode == obj.orderCode)
            obj.planDesc = this.orderinfoResultList[index].planDesc; //index 当前元素索引；1：需要删除的元素个数
          if (this.orderinfoResultList[index].planFinishdate != null) {
            obj.planFinishdate = this.orderinfoResultList[index].planFinishdate;
          }
        });
        //item.planDesc = "满足";
        //item.planFinishdate = "2022-09-11";
      });
    },

    submitPlan() {
      if (this.planProductVOList.length == 0) {
        alert("无排产详情");
        return;
      }

      this.form1.orderIds = this.planOrderinfoList
        .map((item) => item.id)
        .join(",");
      // this.form1.orderPlanList = this.orderplanList;
      this.form1.orderPlanList = [];
      for(let plan of this.planProductVOList) {
        for(let planItem of plan.orderPlanList) {
          this.form1.orderPlanList.push(planItem);
        }
      }

      submitPlan(this.form1).then((response) => {
        this.$modal.msgSuccess("提交排产成功");
        this.open = false;
        this.getList();
      });
    },

    /** 调整排产日期功能 提交按钮 */
    submitForm() {
      this.adjustopen = false;

      if(this.form2.planEndDate1<this.form2.planEndDate){
        alert("调整排产时间只能提前");
        return;
      }

      if(this.form2.planEndDate1>this.form2.planEndDate){

        this.form3.planStartDate=this.form2.planStartDate1;
        this.form3.planEndDate=this.form2.planEndDate1;
        this.form3.adjustEndDate=this.form2.planEndDate;
        this.form3.detailList=this.form2.detailList;
        this.form3.factoryId=this.form2.factoryId;
        this.form3.teamId=this.form2.teamId;
        adjustPlan(this.form3).then((response) => {
          // TODO 只调整了这个值
          this.form2.planStartDate=response.data.adjustStartDate;
          this.form2.planEndDate=response.data.adjustEndDate;
          // 对象引用，需要更新 this.orderplanList里面的值，这个值现在全部在分组里面
          // form2里面的值去找到一个对象引用
          // let temFind = this.orderplanList.find((item) => {
          //   return item.index == this.form2.mId;
          // });
          this.form2.isDelay = 1;
          // let temFind = {};
          for(let plan of this.planProductVOList) {
            for(let planItem of plan.orderPlanList) {
              if (planItem.index === this.form2.mId) {
                // temFind = planItem;
                Object.assign(planItem, this.form2);
                break;
              }
            }
          }
        });
      }
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除订单信息编号为"' + ids + '"的数据项？')
        .then(function () {
          return delOrderinfo(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "orderinfo/orderinfo/export",
        {
          ...this.queryParams,
        },
        `orderinfo_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
